package com.baihuabooks.scoresys.servlets;

import com.alibaba.fastjson.JSON;
import com.baihuabooks.scoresys.common.DBUtil;
import com.baihuabooks.scoresys.common.Page;
import com.baihuabooks.scoresys.entity.Customer;
import com.baihuabooks.scoresys.entity.Response;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Thinkpad on 2016/5/15 0015.
 */
public class CustomerDelServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String customerIds = req.getParameter("ids");

        Response response = new Response();

        if(StringUtils.isBlank(customerIds)) {
            response.setCode(0);
        } else {

            String[] ids = customerIds.split(",");
            List<Integer> intIds = new ArrayList<>();
            for (String id : ids) {
                intIds.add(Integer.valueOf(id.trim()));
            }

            String sql = "DELETE FROM CUSTOMER WHERE ID=?";
            Connection conn = null;
            PreparedStatement stmt = null;
            try {
                conn = DBUtil.getInstance().getConnection();
                stmt = conn.prepareStatement(sql);

                for (Integer intId : intIds) {
                    stmt.setInt(1, intId);
                    stmt.addBatch();
                }
                stmt.executeBatch();
                response.setCode(0);
            } catch (SQLException e) {
                e.printStackTrace();
                response.setCode(1);
                response.setDesc("删除顾客失败");
            } finally {
                DBUtil.close(stmt, conn);
            }
        }

        resp.getWriter().print(response.toString());
    }

}
